<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
    * {
        padding: 0;
        margin: 0;
    }

    canvas {
        display: block;
        background: lightcyan;
    }
    </style>
</head>

<body>
    <canvas id="canvas"></canvas>
    <script>
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    var data = []; //储存小球,运动的时候要用到
    var w, h;

    init();

    function init() {
        w = window.innerWidth;
        h = window.innerHeight;
        canvas.width = w;
        canvas.height = h;
    }
    window.onresize = init;



    function Particle() {
        this.x = random(0, w);
        this.y = random(0, h);
        this.r = random(5, 15);
        this.color = getColor();
        this.vx = random(-5, 5);
        this.vy = random(-5, 5);
    }

    Particle.prototype = {
        draw: function() {
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
            ctx.fillStyle = this.color;
            ctx.fill();
        },
        move: function() {
            /*防止水平方向出界*/
            if (this.x < 0 || this.x > w) {
                this.vx = -this.vx;
            }
            /*防止垂直方向出界*/
            if (this.y < 0 || this.y > h) {
                this.vy = -this.vy;
            }
            this.x += this.vx;
            this.y += this.vy;
            this.draw();
        }

    }
    createParticle(300);
    /*创建一定数量的粒子*/
    function createParticle(num) {
        for (var i = 0; i < num; i++) {
            var particle = new Particle();
            data.push(particle);
        }
    }
    moveParticle();
    /*使粒子运动*/
    function moveParticle() {
        /*每次画之间要清除画布,要不图像都叠加起来了*/
        ctx.clearRect(0, 0, w, h);
        requestAnimationFrame(moveParticle);
        for (var item of data) {
            item.move();
        }
    }
    /*获取范围间的随机数*/
    function random(min, max) {
        return Math.floor(Math.random() * (max - min) + min);
    }
    /*获取随机颜色*/
    function getColor() {
        return `rgb(${random(0,256)},${random(0,256)},${random(0,256)})`;
    }
    </script>
</body>

</html>